<template>
    <div class="login_container">
        <el-row>
            <el-col :span="12" :xs="0"></el-col>
            <el-col :span="12" :xs="24">
                <el-form
                    class="login_form"
                    :model="loginFormData"
                    :rules="rules"
                    ref="ruleFormRef"
                    @keyup.enter="login(ruleFormRef as FormInstance)"
                >
                    <h1>Hello</h1>
                    <h2>欢迎来到Cola课题管理系统，请登录</h2>

                    <el-form-item prop="email">
                        <el-input
                            prefix-icon="User"
                            v-model="loginFormData.email"
                            type="text"
                            placeholder="邮箱"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <div class="code_item">
                            <el-input
                                v-if="loginWay === 0"
                                prefix-icon="Lock"
                                v-model="loginFormData.password"
                                type="password"
                                placeholder="输入密码"
                                show-password
                            ></el-input>
                            <el-input
                                v-else
                                prefix-icon="Key"
                                v-model="loginFormData.password"
                                type="text"
                                placeholder="输入验证码"
                            ></el-input>
                            <code-button
                                v-if="loginWay === 1"
                                :email="loginFormData.email"
                                :formRef="ruleFormRef"
                                type="login"
                            ></code-button>
                        </div>
                    </el-form-item>

                    <el-form-item>
                        <el-button
                            :loading="loading"
                            type="primary"
                            size="default"
                            class="button"
                            @click="login(ruleFormRef as FormInstance)"
                        >
                            登录
                        </el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            :loading="loading"
                            type="primary"
                            size="default"
                            class="button"
                            @click="switchLoginWay"
                        >
                            使用{{ loginWay === 0 ? "验证码" : "密码" }}进行登录
                        </el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button :loading="loading" type="primary" size="default" class="button" @click="goRegister">
                            还没有账号？前往注册
                        </el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button :loading="loading" type="primary" size="default" class="button" @click="goHome">
                            以游客身份访问
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
import { reactive, ref } from "vue";
import { ElNotification } from "element-plus";
import { loginForm } from "@/api/user/type";
import type { FormRules, FormInstance } from "element-plus";
// 引入用户相关的小仓库
import useUserStore from "@/store/modules/user";
// 引入获取时段函数
import { getTime } from "@/utils/time";
// 获取邮箱校验函数
import { isValidEmail } from "@/utils/tools/verify.ts";
import { isEmpty } from "@/utils/tools/isEmpty.ts";
// 获取仓库实例
let userStore = useUserStore();
// 获取路由器
let $router = useRouter();
let $route = useRoute();
// 收集账号与密码的数据
let loginFormData = reactive<loginForm>({
    email: "",
    password: "",
    loginWay: "password",
});
// 定义校验规则
const validateEmail = (_rule: any, value: string, callback: any) => {
    if (isEmpty(value)) {
        return callback(new Error("邮箱不能为空"));
    }
    if (!isValidEmail(value)) {
        return callback(new Error("请输入正确的邮箱"));
    }
    callback();
};
const validatePassword = (_rule: any, value: string, callback: any) => {
    if (isEmpty(value)) {
        return callback(new Error(`${loginWay.value === 0 ? "密码" : "验证码"}不能为空`));
    }
    // 第二个校验只有在使用密码登录时才进行判断
    if (loginWay.value === 0 && (value.length < 6 || value.length > 30)) {
        return callback(new Error("密码长度应在6-30之间"));
    }
    callback();
};
const rules = reactive<FormRules<loginForm>>({
    email: [{ validator: validateEmail, trigger: "blur" }],
    password: [{ validator: validatePassword, trigger: "blur" }],
});
// 定义按钮加载效果
let loading = ref<boolean>(false);
// 获取表单实例
let ruleFormRef = ref<FormInstance>();
const login = ($FormEl: FormInstance) => {
    // 登录时应该对表单进行校验
    $FormEl
        .validate()
        .then(
            () => {
                loading.value = true;
                return userStore.userLogin(loginFormData);
            },
            () => {
                return Promise.reject(new Error("数据不符合要求"));
            },
        )
        .then(
            () => {
                $router.push({
                    path: ($route.query.redirect as string) || "/",
                });
                ElNotification({
                    type: "success",
                    title: `Hi,${getTime()}好`,
                    message: "欢迎回来",
                });
            },
            (error) => {
                ElNotification({
                    type: "error",
                    message: (error as Error).message,
                });
            },
        )
        .finally(() => {
            loading.value = false;
        });
};

// 切换登录方式
const loginWay = ref<number>(0);
const switchLoginWay = () => {
    loginWay.value = loginWay.value === 0 ? 1 : 0;
    loginFormData.loginWay = loginWay.value === 0 ? "password" : "code";
    // 切换时密码（验证码）内容应该清空
    loginFormData.password = "";
    return;
};

// 跳转到注册页面
const goRegister = () => {
    $router.push({ path: "/register", query: { redirect: $route.query.redirect } });
    return;
};
// 跳转到首页
const goHome = () => {
    $router.push({ path: "/home" });
    return;
};
</script>

<style lang="scss" scoped>
.login_container {
    width: 100%;
    height: 100vh;
    background: url("@/assets/images/background.png") no-repeat;
    background-size: cover;
    position: relative;

    .login_form {
        position: relative;
        width: 70%;
        top: 30vh;
        background-color: rgba(59, 55, 113, 0.4);
        background-size: cover;
        padding: 40px;

        h1 {
            color: white;
            font-size: 40px;
        }

        h2 {
            color: white;
            font-size: 20px;
            margin: 20px 0px;
        }

        .el-form-item {
            width: 80%;
            margin-left: auto;
            margin-right: auto;

            .code_item {
                width: 100%;
                display: flex;
                justify-content: space-between;
                flex-wrap: nowrap;

                .el-input {
                    flex-basis: 50%;
                    flex-grow: 1;
                }

                :deep(.get_code_btn) {
                    flex-basis: 30%;
                    flex-grow: 1;
                    margin-left: 20px;
                }
            }
            .button {
                width: 100%;
            }
        }
    }
}
</style>
